import { useState, useCallback, useMemo, memo } from "react";
import { View, Text, TouchableOpacity, ScrollView } from "react-native";
import type { DeptTreeType } from "@/typings/platform";
import { TextInput } from "react-native-paper";
import styles from "./styles";

// https://www.npmjs.com/package/react-native-tree-select
import TreeSelect from "@/components/react-native-tree-select/components/treeSelect";

import AntDesignIcon from "react-native-vector-icons/AntDesign";
import { recursionFind } from "@/utils";

type Props = {
  data: DeptTreeType[];
  defaultSelectedId?: string[];
  change: (e: any) => void;
};

export type StateType = {
  /** 搜索的值 */
  searchVal: string;
  /** 搜索出来的数据 */
  searchValue: Omit<DeptTreeType, "children">[];
};

const _TreeSelect = (props: Props) => {
  const [state, _setState] = useState<StateType>({
    searchVal: "",
    searchValue: []
  });

  // 通用更新状态单个
  const setState = useCallback((field: keyof typeof state, val: any) => {
    _setState(_state => {
      return { ..._state, [field]: val };
    });
  }, []);

  // 通用更新状态(对象)
  const setObjState = useCallback((obj: Partial<typeof state>) => {
    _setState(_state => {
      return { ..._state, ...obj };
    });
  }, []);

  // 行点击
  const handleClick = useCallback(
    (...args: any[]) => {
      console.log("handleClick: ", args);
      if (args[0]) {
        props.change(args[0]);
      }
    },
    [props]
  );

  const closeSearch = useCallback(() => {
    // Keyboard.dismiss();
    setObjState({ searchVal: "", searchValue: [] });
  }, [setObjState]);

  const searchValChange = useCallback(
    (text: string) => {
      setObjState({
        searchVal: text
      });
    },
    [setObjState]
  );

  const searchSubmit = useCallback(() => {
    if (state.searchVal) {
      const res = recursionFind({
        key: "children",
        data: props.data,
        compareFn(val) {
          // console.log("遍历: ", val);
          return val.name.indexOf(state.searchVal) !== -1;
        }
      });
      console.log("res: ", res);
      setObjState({ searchValue: res });
    }
  }, [props.data, setObjState, state.searchVal]);

  const data = useMemo<any>(() => {
    return props.data;
  }, [props.data]);

  const treeNodeStyle = useMemo(() => {
    return {
      openIcon: <AntDesignIcon name="caretdown" size={24} />,
      closeIcon: <AntDesignIcon name="caretright" size={24} />
    };
  }, []);

  const TreeComp = (
    <TreeSelect
      data={data}
      selectType="single"
      defaultSelectedId={props.defaultSelectedId}
      itemStyle={styles.itemStyle}
      selectedItemStyle={styles.selectedItemStyle}
      treeNodeStyle={treeNodeStyle}
      // 类型有问题
      onClick={handleClick}
      // onClickLeaf={val => {
      //   console.log("没有子项: ", val);
      // }}
    />
  );

  const SearchInputRightComp = <TextInput.Icon icon="close" iconColor="rgba(28,27,31,0.5)" onPress={closeSearch} />;

  const SearchInputComp = (
    <TextInput
      dense
      style={styles.searchInput}
      mode="outlined"
      label="请输入机构"
      placeholder="请输入机构"
      value={state.searchVal}
      right={SearchInputRightComp}
      onChangeText={searchValChange}
      onSubmitEditing={searchSubmit}
    />
  );

  const SearchItmsComp = (
    <ScrollView style={styles.searchContainer}>
      {state.searchValue.map(e => {
        return (
          <TouchableOpacity key={e.id} onPress={() => props.change({ item: e })}>
            <Text style={styles.searchItem}>{e.name}</Text>
          </TouchableOpacity>
        );
      })}
    </ScrollView>
  );

  return (
    <View style={styles.container}>
      {SearchInputComp}
      {state.searchValue.length ? SearchItmsComp : TreeComp}
    </View>
  );
};

export default memo(_TreeSelect);
